const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const cheerio = require('cheerio');
const request = require('request');
const timeutil = require('./timeutil');
const NOTICE = 'cloud-edu-notice';
const db = cloud.database()
const _ = db.command;
async function execPromiseAll(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.all(tasks).then(response => {
            resolve(response)
        })
    })
}
async function execRequest(NOTICE_URL) {
    return new Promise(function (resolve, reject) {
        request({
            method: "GET",
            url: NOTICE_URL,
            encoding: 'UTF-8',
            headers: {
                "Referer": "https://www.sdust.edu.cn/sylm/mtkd.htm",
                "Content-Type": "text/html;",
                "Host": "www.sdust.edu.cn",
                "Sec-Fetch-User": "?1",
                "Connection": "keep-alive",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84",
                "cache-control": "max-age=0"
            }
        }, function (error, response, body) {
            // var buf =  iconv.decode(body, 'UTF-8');
            // console.log(buf)
            resolve(response.body)
        })
    })
}
exports.main = async (event, context) => {
    let page = event.page || 1
    /**初始化请求接口 */
    var NOTICE_URL = 'https://www.sdust.edu.cn/kdgg.jsp?totalpage=27&urltype=tree.TreeTempUrl&wbtreeid=1035&PAGENUM=' + page;
    /** 是否对返回结果预处理 */
    let reqRes = await execRequest(NOTICE_URL);
    console.log(reqRes)
    $ = cheerio.load(reqRes);
    $('.sub_item').empty();
    $('.red').empty();
    /**文章地址 List */
    let noticeDateList = [];
    /**文章标题 List */
    let noticeTitleList = [];
    /**总集 List */
    let tmpList = []
    $('li span').each(function (ele, index) {
        let baseStr = $(this).html()
        // console.log(baseStr)
        if (baseStr != '') {
            tmpList.push(baseStr)
        }
    })
    /**遍历并构建 */
    for (var i = 0; i < tmpList.length; i++) {
        if (i % 2 == 0) {
            noticeTitleList.push(tmpList[i])
        } else {
            noticeDateList.push(tmpList[i])
        }
    }
    let noticeLen = noticeTitleList.length;
    let noticeList = [];
    /**查询列表 */
    let noticeUrlList = []
    for (var i = 0; i < noticeLen; i++) {
        let idSelect = '#line_u8_' + i + ' a';
        try {
            let baseId = $(idSelect).attr('href').trim();
            console.log(baseId)
            let obj = {};
            obj.noticeUrl = baseId
            noticeUrlList.push(baseId)
            obj.noticeTitle = noticeTitleList[i];
            obj.noticeDate = noticeDateList[i];
            noticeList.push(obj)
        } catch (error) {
            console.log(error)
        }

    }
    console.log(noticeList)
    /**查询在列表中的元素 */
    let hasUrlListRes = await db.collection(NOTICE).where({
        noticeUrl:_.in(noticeUrlList)
    }).get();
    console.log(hasUrlListRes)
    let hasUrlListResData = hasUrlListRes.data;
    /**整理已写入 */
    let hasUrlList = [];
    hasUrlListResData.forEach(function(ele,index){
        hasUrlList.push(ele.noticeUrl)
    })

    /**构建写入任务 */
    let addTasks = [];
    noticeList.forEach(function(ele,index){
        if(hasUrlList.indexOf(ele.noticeUrl) == -1){
            addTasks.push(db.collection(NOTICE).add({
                data:{
                    noticeDate:ele.noticeDate,
                    noticeUrl:ele.noticeUrl,
                    noticeTitle:ele.noticeTitle,
                    _createTime:timeutil.TimeCode(),
                    _updateTime:timeutil.TimeCode()
                }
            }))
        }
    })
    let execRes = await execPromiseAll(addTasks);
    return execRes;
    // console.log(baseId)

}